package com.example.synatx.lombda;

import com.example.synatx.lesson2.Apple;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.function.Supplier;

import static java.util.Comparator.comparing;

/**
 * 方法引用
 * 方法引用主要有一下几类:
 * 1.指向静态方法的方法引用,比如Integer.parseInt => Integer::parseInt
 * 2.指向任意类型实例方法的方法引用,比如String.length => String::length
 * 3.指向现有对象的实例方法的方法引用
 */
public class MethodReferenceTest {

    public void test01(){
        List<Apple> apples = new ArrayList<>();
        apples.sort( (Apple a1,Apple a2) -> {
            return a2.getWeight().compareTo(a1.getWeight());
        });
        apples.sort(comparing(Apple::getWeight));

    }

    public void test02(){
        List<String> list = Arrays.asList("a","A","b","d");
        list.sort((s1,s2)->s1.compareToIgnoreCase(s2));

        list.sort(String::compareToIgnoreCase);
    }

    //构造函数引用

    public void test03(){
        Supplier<Apple> appleSupply = Apple::new;
        Apple apple = appleSupply.get();

        Function<Double,Apple> appleFunction = Apple::new;
        Apple apple1 = appleFunction.apply(100D);


        List<Double> doubles = Arrays.asList(1d,2d,3d,5d);
        List<Apple> apples = map(doubles,appleFunction);

    }

    public static List<Apple> map(List<Double> list,Function<Double,Apple> f){
        List<Apple> result = new ArrayList<>();
        for(Double d : list){
            result.add(f.apply(d));
        }
        return result;
    }
}
